#include "WindowEventHandler.h"
#include "GameSystemManager.h"

bool WindowEventHandler::showDebugInfo = false;
std::string WindowEventHandler::mDebugText = "";

WindowEventHandler::WindowEventHandler()  {
	mWindow = GameSystemManager::getSingleton()->getOgre()->getWindow();
	WindowEventUtilities::addWindowEventListener(mWindow, this);
	windowResized(mWindow);
}

WindowEventHandler::~WindowEventHandler() {
	
}

void WindowEventHandler::windowResized(RenderWindow* rw)
{
	unsigned int width, height, depth;
	int left, top;
	rw->getMetrics(width, height, depth, left, top);
	
	GameSystemManager::getSingleton()->getInput()->updateMouseMetrics(width,height);
}

void WindowEventHandler::windowClosed(RenderWindow* rw)
{
	//tell other systems to shutdown
	//GameSceneManager::getSingleton()->~GameSceneManager();
}

void WindowEventHandler::update()
{
	//This force the window to get rendered even if it doesnt has the focus, for testing porpouses only
	if(!mWindow->isActive()) 
		mWindow->setActive(true);

	if(showDebugInfo)
		updateStats();

}

void WindowEventHandler::windowFocusChange(RenderWindow* rw) {
	
}

void WindowEventHandler::updateStats()
{
    static String currFps = "Current FPS: ";
    static String avgFps = "Average FPS: ";
    static String bestFps = "Best FPS: ";
    static String worstFps = "Worst FPS: ";
    static String tris = "Triangle Count: ";

    // update stats when necessary
    OverlayElement* guiAvg = OverlayManager::getSingleton().getOverlayElement("Core/AverageFps");
    OverlayElement* guiCurr = OverlayManager::getSingleton().getOverlayElement("Core/CurrFps");
    OverlayElement* guiBest = OverlayManager::getSingleton().getOverlayElement("Core/BestFps");
    OverlayElement* guiWorst = OverlayManager::getSingleton().getOverlayElement("Core/WorstFps");
    
    guiAvg->setCaption(avgFps + StringConverter::toString(mWindow->getAverageFPS()));
    guiCurr->setCaption(currFps + StringConverter::toString(mWindow->getLastFPS()));
    guiBest->setCaption(bestFps + StringConverter::toString(mWindow->getBestFPS())
        +" "+StringConverter::toString(mWindow->getBestFrameTime())+" ms");
    guiWorst->setCaption(worstFps + StringConverter::toString(mWindow->getWorstFPS())
        +" "+StringConverter::toString(mWindow->getWorstFrameTime())+" ms");
        
    OverlayElement* guiTris = OverlayManager::getSingleton().getOverlayElement("Core/NumTris");
    guiTris->setCaption(tris + StringConverter::toString(mWindow->getTriangleCount()));

    OverlayElement* guiDbg = OverlayManager::getSingleton().getOverlayElement("Core/DebugText");
    guiDbg->setCaption(mDebugText);
}
